import axios, { AxiosRequestConfig } from 'axios';
// 引入配置文件
import requstConfig from './request.config';

// 获取语言编码
const getLanguageCode = ()=>{
    const loanguageCode = localStorage.getItem('languageCode') || navigator.language || "en_US";
    return loanguageCode.replace("_","-");
}

// 获取地址
const getRootAddress = ()=>{
    const rootAddress = localStorage.getItem('rootAddress') || requstConfig.rootAddress;
    return rootAddress;
}

// 创建axios实例
const requestAxios = axios.create({
    baseURL: requstConfig.rootAddress,
    timeout: 5000, // 请求超时时间
    headers: {
        "token":sessionStorage.getItem(requstConfig.tokenStroageKey),
        "languageCode":getLanguageCode()
    }
});

// request拦截器
requestAxios.interceptors.request.use(
    config => {
        // 在发送请求之前做些什么
        return config;
    },
    error => {
        // 请求超时
        if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1) {
            console.log('timeout请求超时');
        }
    }
);

const request = (param:any)=>{
    return requestAxios({
        ...param,
        headers: {
            ...param.headers,
            "token":localStorage.getItem(requstConfig.tokenStroageKey),
            "languageCode":getLanguageCode()
        },
    });
}

const setToken = (token:string)=>{
    localStorage.setItem(requstConfig.tokenStroageKey,token);
}

const getToken = ()=>{
    return localStorage.getItem(requstConfig.tokenStroageKey);
}


export default {
    request,
    setToken,
    getToken,
    getRootAddress
};
